#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param);

#BEGIN { $Exporter::Verbose=1 }

# Startupscript translater
my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];
my $option4 = $ARGV[6];


my $backHeader="black";
my $httpUser = $ENV{'REMOTE_USER'};
my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $httpUserIp = $ENV{'REMOTE_ADDR'};
my $httpServerName = $ENV{'HTTP_HOST'};
my $httpCookie = $ENV{'HTTP_COOKIE'};
my $httpHost = $ENV{'HTTP_HOST'};
my $syslogInfoDir = $ENV{'SIM_SYSLOGINFOD'};
my $syslogDir = $ENV{'SIM_SYSLOGD'};

my @errorColors = qw ( FF00FF FF0000 FF8800 FFFF00 DDFF00 00FF00 33FFFF );
my @errorNames = qw ( Allert Immediate Critical Error Warning Normal Informational );

sub catFile {
  my $output = "";
  my ($file) = @_;
  open FH, $file or $output = "none";
# $output = readline FH;
  $output = <FH>;
  close FH;
  return $output;
}

sub catFileLine {
  my $outPut = "";
  my ($file) = @_;
  open FH, $file or $outPut = "$file";
  $outPut = <FH>;
  close FH;
  chomp($outPut);  # remove the newline
  return $outPut;
}

sub printFileLine {
  my $file = "@_[0]";
  my $varName = "@_[1]";
  my $rest = "@_[2]";
  my $logFile = "@_[3]";
  my $oldVal = catFileLine ("$file");
# print ("Update file=$file, varName=$varName, content:$rest<BR>");
  if ( "$oldVal" ne "$rest" ) {
    open(OUT, ">$file") || die "cannot create $file: $! (file=$file, varName=$varName, rest=$rest)";
    if ( "$logFile" ne "quiet" ) {
      print ("$varName is gewijzigd, oud:$oldVal nieuw:$rest<BR>");
    }
    print OUT $rest;
    close(OUT);
  }
}

sub testParam {
  my $file = "@_[0]";
  my $parameter = "@_[1]";
  my $update = "@_[2]";
  my $result = param("$parameter");
  if ( "$result" eq "" ) {
#   print("cat ");
    $result = &catFileLine("$file");
  } else {
    if ( "$update" eq "upd" ) { 
      printFileLine("$file","$parameter","$result","nquiet");
    }
  }
# print("$result $file<BR>");
  return("$result");
}

sub testNameStrict {
  my $testname = "@_[0]";
  my $type = "@_[1]";
  if ( "$type" eq "word" ) {
    $testname =~ tr#a-zA-Z[\xE0][\xE8][\xEC][\xF2][\xF9]##cd;
  } else {
    $testname =~ tr#a-zA-Z0-9[\@][\.][\-]#A#cds;
  }
  #print ("testname=$testname");
  return $testname;
}

sub testMkDir {
  my $dirName = "@_[0]";
  if ( !-d $dirName ) {
    system "mkdir -p $dirName";
  }
}

sub printHead {
  my $dispHead = "@_[0]";
  print("
        <TABLE WIDTH=100% BORDER=0 CELLSPACING=0><TR BGCOLOR=#EEEEEE><TD COLSPAN=3><CENTER>
        Options:
        <A HREF=$httpScriptName?$module+$tool+list>List</A>
	</TD></TR>
	</TABLE>
        ");
}

sub readUpdParam {
  my $workDir = "@_[0]";
  my $name = "@_[1]";
  my $type = "@_[2]";
  my $param = param("$name");
  if ( "$type" eq "fill" ) {
    $param=~s/ /_/g;
  }
  if ( "$param" eq "" ) {
    $param = catFileLine("$workDir");
  } else {
    printFileLine("$workDir","$name","$param");
  }
  return $param;
}

sub printDir {
  my $baseAction = "@_[0]";
  my $baseParam = "@_[1]";
  my $workDir = "@_[2]";
  if ( -d $workDir ) {
    chdir "$workDir";
    my @list = <*>;
    print("<TABLE>");
    foreach my $entry (@list) {
      my $type = "";
      if (( substr($entry, 0, 3) eq "ASA" ) or ( substr($entry, 0, 3) eq "PIX" )) {
        $type = substr($entry, 6, 6);
      } elsif ( substr($entry, 0, 4) eq "FWSM" ) {
        $type = substr($entry, 7, 6);
      } else {
        $type = $entry;
      }
      my $infoDir = "$syslogInfoDir/messages/$type";
      my $testFile = "$infoDir/messageString";
      my $testColorNum = catFileLine( "$infoDir/severity" );
      my $testColorType;
      if ( "$testColorNum" ne "" ) {
        $testColorType = $errorColors[$testColorNum];
      } else {
        $testColorType = "DDDDDD";
      }
      my $syslogMessage = "";
      if ( -f $testFile ) {
        $syslogMessage = catFileLine( "$testFile" );
#       print(" <TR><TD COLSPAN=3>-> $syslogMessage</TD></TR>");
      }
      my $statusImg;
      if ( -f "$infoDir/skipError" ) {
        $statusImg = "/sipman3/gifs/flag_red.png";
      } else {
        $statusImg = "/sipman3/gifs/flag_green.png";
      }
      print("<TR>
              <TD BGCOLOR=#$testColorType><A HREF=$httpScriptName?$module+$tool+${baseAction}${baseParam}+$entry>$entry</A></TD>
              <TD>
               <A HREF=$httpScriptName?$module+$tool+updMessage+${type}${baseParam}+${entry}>
                 <IMG SRC=$statusImg BORDER=0>
               </A></TD>
              <TD>$syslogMessage</TD>
             </TR>");
    }
    print("</TABLE>");
  } else {
    print ("OOps, directory ($workDir) not found....");
  }
}

sub searchFiles {
   my $logFileD = "@_[0]";
   my $deviceName = "@_[1]";
   my $fileName = "@_[2]";
   my $string1 = param("string1");
   my $string2 = param("string2");
   my $fileString = "\*";
   if (( "$fileName" ne "" ) and ( -f "$syslogDir/$logFileD/$deviceName/$fileName" )) {
     $fileString = $fileName;
   }
   if ( -d "$syslogDir/$logFileD/$deviceName" ) {
     print("<CENTER>Searching for $string1 in 
              <A HREF=$httpScriptName?$module+$tool+list+$logFileD>$logFileD</A> =&gt; 
              $deviceName =&gt; $fileString<HR><PRE>");
     chdir("$syslogDir/$logFileD/$deviceName");
     if ( "$string2" eq "" ) {
       system(" grep -h -i \"$string1\" $fileString ");
     } else {
       system(" grep -h -i \"$string1\" $fileString | grep -i \"$string2\" ");
     }
     print("</PRE>");
   }
}

sub list {
   my $logFileD = "@_[0]";
   my $deviceName = "@_[1]";
   my $fileName = "@_[2]";
   print("<CENTER>");
   if ( "$deviceName" ne "" ) {
     print("
       <FORM method=post Action=$httpScriptName?$module+$tool+search+$logFileD+$deviceName+$fileName>
         Search: <INPUT NAME=string1 SIZE=20> and <INPUT NAME=string2 SIZE=20>
         <INPUT TYPE=submit Value=\"Search\">
       </FORM>
           ");
   }
   if ( -f "$syslogDir/$logFileD/$deviceName/$fileName" ) {
     my $type;
     if (( substr($fileName, 0, 3) eq "ASA" ) or ( substr($fileName, 0, 3) eq "PIX" )) {
        $type = substr($fileName, 6, 6);
     } elsif ( substr($fileName, 0, 4) eq "FWSM" ) {
        $type = substr($fileName, 7, 6);
     } else {
        $type = $fileName;
     }
     print("<B>Info for: 
             <A HREF=$httpScriptName?$module+$tool+list+$logFileD>$logFileD</A>
               -&gt; 
             <A HREF=$httpScriptName?$module+$tool+list+$logFileD+$deviceName>$deviceName</A>
               -&gt; 
             <A HREF=$httpScriptName?$module+$tool+updMessage+$type+$logFileD+$deviceName+$fileName>$fileName</A>
            </B><HR>");
     print("<TABLE><TR><TD><PRE>");
     my $logFile = "$syslogDir/$logFileD/$deviceName/$fileName";
     if ( ! -r $logFile ) {
       print("Oops, unable to read logfile: $logFile.");
     } else {
       open( LOG, $logFile ) || die ("Oops, problems reading $logFile!!!");
       my @info = <LOG>;
       close LOG;
       my @revLog = reverse(@info);
       foreach my $line (@revLog) {
         print("$line");
       }
     }
#    system(" cat $syslogDir/$logFileD/$deviceName/$fileName ");
     print("</PRE></TD></TR></TABLE>");
   } elsif ( "$logFileD" eq "none" ) {
     print("<B>Main syslog level.</B><HR>");
     my $workDir = "$syslogDir";
     printDir( "list", "", $workDir );
   } elsif ( "$deviceName" eq "" ) {
     print("<B>Directory entries for: $logFileD</B><HR>");
     my $workDir = "$syslogDir/$logFileD";
     printDir( "list", "+$logFileD", $workDir );
   } elsif ( "$fileName" eq "" ) {
     print("<B>File entries for: 
             <A HREF=$httpScriptName?$module+$tool+list+$logFileD>$logFileD</A> -&gt; $deviceName</B><HR>");
     my $workDir = "$syslogDir/$logFileD/$deviceName";
     printDir( "list", "+$logFileD+$deviceName", $workDir );
   }
}

sub updMessage {
  my $messageNum = "@_[0]";
  my $logFileD = "@_[1]";
  my $deviceName = "@_[2]";
  my $fileName = "@_[3]";
  my $workDir = "$syslogInfoDir/messages/$messageNum";
  testMkDir($workDir);
  my $messageString = readUpdParam("$workDir/messageString","messageString");
  my $severity = readUpdParam("$workDir/severity","severity");
  my $extraAction = readUpdParam("$workDir/extraAction","extraAction");
  if ( $severity eq "" ) {
    $severity = "5";
  }
  my $reportError = param("reportError");
  if ( "$reportError" eq "" ) {
    if ( -f "$workDir/skipError" ) {
      my $reportInfo = catFileLine("$workDir/skipError");
      if ( "$reportInfo" eq "filter" ) {
        $reportError = "filter";
      } else {
        $reportError = "no";
      }
    } else {
      $reportError = "yes";
    }
  } else {
    if (( "$reportError" eq "yes" ) and ( -f "$workDir/skipError" )) {
      unlink("$workDir/skipError");
    } elsif ( "$reportError" eq "no" ) {
      printFileLine("$workDir/skipError","skip","skip report");
    } elsif ( "$reportError" eq "filter" ) {
      printFileLine("$workDir/skipError","filter","filter");
    }
  }
  my $messagesFile = "$syslogDir/$logFileD/$deviceName/$fileName";
  print("$messagesFile<HR>");
  if ( -f $messagesFile ) {
    print("<PRE>");
    system(" tail $messagesFile");
    print("</PRE><HR>");
  }
  print("<CENTER><TABLE>
    <FORM method=post Action=$httpScriptName?$module+$tool+updMessage+$messageNum+$logFileD+$deviceName+$fileName>
    <TR><TD>Message numbre</TD><TD>$messageNum</TD></TR>
    <TR><TD>Message string</TD><TD><INPUT NAME=\"messageString\" SIZE=80 VALUE=\"$messageString\"></TD></TR>
        ");
  if ( -f $messagesFile ) {
    print("
      <TR><TD>Severity</TD><TD><SELECT NAME=severity>
         <OPTION VALUE=$severity>$errorNames[$severity] ($severity)</OPTION>
        ");
    for my $count (0..6) {
      print("<OPTION VALUE=$count>$errorNames[$count] ($count)</OPTION>");
    }
    print("</SELECT></TD></TR>
      <TR><TD>Report to errorlog</TD><TD><SELECT NAME=reportError>
         <OPTION VALUE=$reportError>$reportError</OPTION>
         <OPTION VALUE=yes>yes</OPTION>
         <OPTION VALUE=no>no</OPTION>
         <OPTION VALUE=filter>filter</OPTION>
      </SELECT></TD></TR>
      </SELECT></TD></TR>
      <TR><TD>Aditional action</TD><TD><SELECT NAME=extraAction>
         <OPTION VALUE=$extraAction>$extraAction</OPTION>
         <OPTION VALUE=sms>sms</OPTION>
         <OPTION VALUE=email>email</OPTION>
         <OPTION VALUE=downloadConfig>download config</OPTION>
         <OPTION VALUE=none>none</OPTION>
      </SELECT></TD></TR>
          ");
  }
  print("
    </TABLE>
    <INPUT TYPE=submit Value=\"Update\">
       ");
}

#--------------------------- Main ---------------------------
printHead;



if ( "$action" eq "updMessage" ) {
  updMessage( $option1, $option2, $option3, $option4);
} elsif ( "$action" eq "search" ) {
  searchFiles ( $option1, $option2, $option3);
} else {
  list( $option1, $option2, $option3 );
}
